<template>
  <div class="sub-filter" v-if="filterData &&!filterLoading">
    <div class="item">
      <div class="head">品牌:</div>
      <div class="body">
        <a href="JavaScript:;" v-for="brand in filterData.brands" :key="brand.id">{{brand.name}}</a>
      </div>
    </div>
    <div class="item" v-for="p in filterData.saleProperties" :key="p.id">
      <div class="head">{{p.name}}：</div>
      <div class="body">
        <a href="JavaScript:;" v-for="sub in p.properties" :key="sub.id">{{sub.name}}</a>
      </div>
    </div>
  </div>
  <div v-else class="sub-filter">
    <XtxSkeleton class="item" width="800px" height="40px" />
    <XtxSkeleton class="item" width="800px" height="40px" />
    <XtxSkeleton class="item" width="600px" height="40px" />
    <XtxSkeleton class="item" width="600px" height="40px" />
    <XtxSkeleton class="item" width="600px" height="40px" />
  </div>
</template>

<script>
import { findSubCategory } from '@/api/category'
import { useRoute } from 'vue-router'
import { ref, watch } from 'vue'
export default {
  name: 'SubFilter',
  setup() {
    // 1. 获取数据
    // 2. 数据中需要全部选中，需要预览将来点击激活功能。默认选中全部
    // 3. 完成渲染
    const route = useRoute()
    const filterData = ref({})
    const filterLoading = ref(false)
    // 4. 分类发生变化的时候需要重新获取筛选数据，需要使用侦听器
    watch(() => route.params.id, (newVal) => {
      // newVal有值且id是二级类目的id (route.path 当前路由地址)
      if (newVal && (`/category/sub/${newVal}`) === route.path) {
        filterLoading.value = true
        findSubCategory(route.params.id).then(data => {
          // 增加品牌（全部）
          data.result.brands.unshift({ id: null, name: '全部' })
          // 增加销售属性（全部）
          data.result.saleProperties.forEach(p => {
            p.properties.unshift({ id: null, name: '全部' })
          })
          filterData.value = data.result
          filterLoading.value = false
        })
      }
    }, { immediate: true })
    return { filterData }
  }

}
</script>

<style scoped lang='less'>
.XtxSkeleton {
  padding: 10px 0;
}
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    line-height: 40px;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        display: inline-block;
        &.active,
        &:hover {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>